import styles from "./index.module.css";
import { Button, Input, Space, Upload, message } from "antd";
import { useEffect, useState } from "react";
import { electronApiType } from "../../../../preload";
import {
  FileSelector,
  FileSelectorType,
} from "../../components/DirectoryChooser/DirectoryChooser";
import axios from "axios";

type OmitFirstArg<F> = F extends (x: any, ...args: infer P) => infer R
  ? (...args: P) => R
  : never;
declare global {
  interface Window {
    electronAPI: {
      [key in keyof electronApiType]: OmitFirstArg<electronApiType[key]>;
    };
  }
}

const Server = (props: {
  setLocalhost: (val: string) => void;
  localHost: string;
  setIndexFileName: (val: string) => void;
  clearInput: () => void;
  setUpload: (arg: (val: FileSelectorType) => FileSelectorType) => void;
  setUploadFrom: (path: string) => void;
  uploadFrom: string;
}) => {
  const [serverStatus, setServerStatus] = useState(true);
  // const [upload, setUpload] = useState<FileSelectorType>({
  //   emit: false,
  //   type: "dir",
  //   callBack: (path: string, fileList: FileList) => {},
  // });

  useEffect(() => {
    console.log("init");
    window.addEventListener("unload", function () {
      window.electronAPI.stopServer();
    });
  }, []);
  return (
    <Space>
      <Button
        type="primary"
        onClick={() => {
          if (serverStatus) {
            props.clearInput();
            window.electronAPI.startServer().then((url: string) => {
              props.setLocalhost(url);
            });
          } else {
            props.setLocalhost("unknown");
            props.setIndexFileName("");
            window.electronAPI.stopServer();
            props.setUploadFrom("");
          }
          setServerStatus((val) => !val);
        }}
      >
        {serverStatus ? "start server" : "stop server"}
      </Button>
      {/* <Button onClick={() => {}}>upload formatted project</Button> */}
      <Button
        type="primary"
        onClick={() => {
          props.setUpload((e) => ({
            emit: !e.emit,
            type: "dir",
            callBack: (path: string, fileList: FileList) => {
              // uploadFrom = path;
              props.setUploadFrom(path);
              window.electronAPI.setUploadFolderPath(path);

              const pro = window.electronAPI.checkStructure(path);
              pro.catch(() => {
                let fd = new FormData();
                for (let i = 0; i < fileList.length; i++) {
                  if (fileList[i].size === 0) {
                    continue;
                  }
                  fd.append("file", fileList[i]);
                }
                // fd.append("uploadFolderPath", path);

                axios
                  .post(props.localHost + "upload", fd, {
                    headers: {
                      "Content-Type": "multipart/form-data",
                    },
                  })
                  .then((response) => {
                    // console.log("upload success", response.data);
                  })
                  .catch((error) => {
                    console.error("upload failed!", error);
                    return Promise.reject();
                  })
                  .then(() => {
                    window.electronAPI.detectIndex().then((name) => {
                      props.setIndexFileName(name);
                      message.success("upload success!");
                    });
                  });

                message.warning(
                  "this folder is not a formated folder please link resource first!!!"
                );
              });
              pro.then(() => {
                window.electronAPI.copyQualifiedStructure(path).then((name) => {
                  window.electronAPI.detectIndex().then((name) => {
                    props.setIndexFileName(name);
                    message.success("upload success!");
                  });
                });
              });
            },
          }));
        }}
      >
        upload project
      </Button>
      {/* <Button type="primary" onClick={() => window.electronAPI.examine()}>
        examine before upload
      </Button> */}
      <Button
        onClick={() => {
          window.electronAPI.openUrl(props.localHost).catch(() => {
            message.error("please start server first!");
          });
        }}
      >
        open in browser
      </Button>
      <Button
        onClick={() => {
          if (props.localHost === "unknown") {
            message.error("start server first!");
            return;
          }
          window.electronAPI.openProjectFolder(props.localHost).catch(() => {
            message.error("please start server first!");
          });
        }}
      >
        open project folder
      </Button>

      <Button
        onClick={() => {
          window.electronAPI
            .writeBack(props.uploadFrom)
            .then(() => {
              message.success("write success!");
            })
            .catch((err) => {
              message.error("write error!");
              console.log(err);
            });
        }}
      >
        write back
      </Button>
      <Button
        onClick={() => {
          if (props.localHost === "unknown") {
            message.error("start server first!");
            return;
          }
          window.electronAPI.openOriginFolder().catch(() => {
            message.error("please upload first!");
          });
        }}
      >
        open origin folder
      </Button>
      <a href={props.localHost}>{props.localHost}</a>
      <Button
        onClick={() => {
          if (props.localHost === "unknown") {
            message.error("start server first!");
            return;
          }
          window.electronAPI.vscode().catch(() => {
            message.error("please upload first!");
          });
        }}
      >
        vscode
      </Button>
      <Button
        onClick={() => {
          window.electronAPI.openCmdWithPath();
        }}
      >
        open project in cmd
      </Button>
    </Space>
  );
};

export const Index = () => {
  const [localhost, setLocalhost] = useState("unknown");
  const [name, setName] = useState({
    oldName: "",
    newName: "",
  });
  const [indexName, setIndexName] = useState("");
  const [backupFolder, setBackupFolder] = useState("");
  const [upload, setUpload] = useState<FileSelectorType>({
    emit: false,
    type: "dir",
    callBack: (path: string, fileList: FileList) => {},
  });
  const [uploadFrom, setUploadFrom] = useState("");
  const { TextArea } = Input;
  const [info, setInfo] = useState("");
  const [hei, setHei] = useState<number>(100);

  const checkIndex = () => {
    if (indexName.endsWith(".html") || indexName.endsWith(".htm")) return true;
    message.error("please check index file name first!");
    return false;
  };

  useEffect(() => {
    window.electronAPI
      .getStorage("backupPath")
      .then((path) => setBackupFolder(path || "unknown"));
  }, []);

  return (
    <div>
      <FileSelector upload={upload} />
      <Server
        setUpload={setUpload}
        setLocalhost={setLocalhost}
        localHost={localhost}
        setIndexFileName={setIndexName}
        uploadFrom={uploadFrom}
        setUploadFrom={setUploadFrom}
        clearInput={() => {
          setIndexName("");
          setName({
            oldName: "",
            newName: "",
          });
        }}
      />
      <br />
      <Space className={styles.gap}>
        <Button
          onClick={() => {
            window.electronAPI.linkRes();
            message.success("link resource success!");
          }}
        >
          link resources
        </Button>
        <Button
          onClick={() => {
            window.electronAPI.clearLink();
          }}
        >
          clear http link
        </Button>
        <Button
          onClick={() => {
            window.electronAPI.integration();
          }}
        >
          integration
        </Button>
        <Button
          onClick={() => {
            window.electronAPI.unlinkImg();
          }}
        >
          unlink img
        </Button>
        <Button
          onClick={() => {
            window.electronAPI.beautify();
          }}
        >
          beautify
        </Button>
        height: <Input value={hei} onChange={(e) => setHei(+e.target.value)} />
        <Button
          onClick={() => {
            window.electronAPI.categoryEquipments(hei);
          }}
        >
          category equipment
        </Button>
        {/* <Button
          onClick={() => {
            checkIndex() && window.electronAPI.merge(indexName);
          }}
        >
          merge iframe
        </Button>
        <Button
          onClick={() => {
            window.electronAPI.merge2(indexName);
          }}
        >
          test
        </Button> */}
      </Space>
      <br />
      <Space className={styles.gap}>
        old name:{" "}
        <Input
          value={name.oldName}
          onChange={(val) =>
            setName((e) => ({ ...e, oldName: val.target.value }))
          }
        />
        new name:{" "}
        <Input
          value={name.newName}
          onChange={(val) =>
            setName((e) => ({ ...e, newName: val.target.value }))
          }
        />
        <Button
          onClick={() => {
            window.electronAPI.rename(name.oldName, name.newName);
          }}
          type="primary"
        >
          replace text and title
        </Button>
        <Button
          onClick={() => {
            window.electronAPI.renameTitle(name.newName);
          }}
          type="primary"
        >
          only replace title
        </Button>
      </Space>
      <br />
      <Space className={styles.gap}>
        <Input
          value={indexName}
          onChange={(e) => setIndexName(e.target.value)}
        />
        add functions:
        <Button
          onClick={() => {
            checkIndex() && window.electronAPI.footer(indexName);
          }}
        >
          footer
        </Button>
        <Button
          onClick={() => {
            checkIndex() && window.electronAPI.zoom(indexName);
          }}
        >
          zoom
        </Button>
        <Button
          onClick={() => {
            checkIndex() && window.electronAPI.addMusic(indexName);
          }}
        >
          music
        </Button>
        <Button
          onClick={() => {
            checkIndex() && window.electronAPI.addIcon(indexName);
          }}
        >
          icon
        </Button>
        <Button
          onClick={() => {
            checkIndex() && window.electronAPI.addQQ(indexName);
          }}
        >
          qq
        </Button>
      </Space>
      <br />
      <Space className={styles.gap}>
        <Button
          onClick={() => {
            // console.log(
            //   uploadFrom.replace(/\\/g, "/"),
            //   backupFolder.replace(/\\/g, "/")
            // );
            window.electronAPI
              .backup(
                uploadFrom.replace(/\\/g, "/"),
                backupFolder.replace(/\\/g, "/")
              )
              .then((mes) => message.success(mes))
              .catch((err) => {
                message.error(JSON.stringify(err.message));
              });
          }}
        >
          backup
        </Button>
        <Button
          onClick={() => {
            window.electronAPI
              .getStorage("backupPath")
              .then((path) =>
                window.electronAPI.openFolder(path).catch((err) => {
                  message.error(JSON.stringify(err));
                })
              )
              .catch((err) => {
                message.error(JSON.stringify(err.message));
              });
          }}
        >
          open backup folder
        </Button>
        <Button
          onClick={() => {
            window.electronAPI.fileSelector("dir").then((res) => {
              const path = res.filePaths[0];
              window.electronAPI.setStorage("backupPath", path);
              setBackupFolder(path);
            });
            // setUpload({
            //   emit: !upload.emit,
            //   type: "dir",
            //   callBack: (path: string, fileList: FileList) => {
            //     console.log(path);
            //     window.electronAPI.setStorage("backupPath", path);
            //     setBackupFolder(path);
            //   },
            // });
          }}
        >
          choose folder
        </Button>
        <span>{uploadFrom}</span> ===&gt;
        <span>{backupFolder}</span>
        <Button
          onClick={() =>
            window.electronAPI.fileSelector("file").then((val) => {
              window.electronAPI.videoPoster(val).then((snippet) => {
                setInfo(snippet);
              });
            })
          }
        >
          video poster
        </Button>
      </Space>
      <br />
      <Space className={styles.gap}>
        <Button onClick={() => window.electronAPI.test()}>test</Button>
        <Button onClick={() => window.electronAPI.electronProjectFolder()}>
          electron project folder
        </Button>
      </Space>
      <br />
      <TextArea
        className={styles.gap}
        value={info}
        onChange={(e) => setInfo(e.target.value)}
        style={{ width: "800px", height: "200px" }}
      />
    </div>
  );
};
